﻿@model MvcTemplates.Model.CheckBoxList
@using MvcTemplates

@{   
    var count = Model.Options.Count();
    var name = ViewData.TemplateInfo.GetFullHtmlFieldName( "SelectedOptions" );
    var selectedOptionsAsStrings = Model.SelectedOptions.Select( x => x.ToString() ).ToList();
    
    var modelStateValue = Html.GetModelStateValue( name, typeof(object[]) ) as object[];
    
    if ( modelStateValue != null )
    {
        selectedOptionsAsStrings = modelStateValue.Select( x => x.ToString() ).ToList();
    }
    
    var checkBox = new CloneableTagBuilder( "input" );
    checkBox.AddCssClass( Html.GetProfile().CheckBoxListClasses );
    checkBox.Attributes["type"] = "checkbox";
    checkBox.Attributes["name"] = name;
    
    for( int i = 0; i < count; i++ ){
       
        var item = Model.Options.ElementAt( i ); 
               
        var id = string.Format( "{0}_{1}", ViewData.TemplateInfo.GetFullHtmlFieldId("Value"), i );    
        var value = item.Value ?? item.Text;
        var isChecked = item.Selected || selectedOptionsAsStrings.Contains( value );   
        
        var clonedBox = (CloneableTagBuilder) checkBox.Clone();
        clonedBox.Attributes["id"] = id;
        clonedBox.Attributes["value"] = value;
        if ( isChecked )
        {
            clonedBox.Attributes["checked"]="checked";   
        }
        
        TemplateHelpers.MergeAttributes( ViewData.ModelMetadata.MergeAttributes<HtmlAttributesAttribute>( null ), checkBox.Attributes );
        
        @Html.C( x => x.CheckBoxListCheckBoxContainer, TagRenderMode.StartTag, additionalIdAppender: i.ToString() )
            @MvcHtmlString.Create( clonedBox.ToString() )
            <label for="@id">@item.Text</label>        
        @Html.C( x => x.CheckBoxListCheckBoxContainer, TagRenderMode.EndTag )
    }
}